<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/Welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row :gutter="10">
        <el-col :span="7">
          <el-input clearable @clear="getUserList" placeholder="请输入内容" v-model="paramList.query">
            <el-button slot="append" icon="el-icon-search" @click="queryUserBykey"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="AddDialogVisible = true">
            添加用户
          </el-button>
          <el-dialog
            title="添加用户"
            :visible.sync="AddDialogVisible"
            width="40%"
            @close="$refs.addUserRef.clearValidate()">
            <el-form status-icon :model="userInfo" :rules="addRules" ref="addUserRef">
              <el-form-item prop="username" label="用户名" label-width="70px" hide-required-asterisk>
                <el-input clearable v-model="userInfo.username" placeholder="请输入用户名"></el-input>
              </el-form-item>
              <el-form-item prop="password" label="密码" label-width="70px" hide-required-asterisk>
                <el-input clearable v-model="userInfo.password" placeholder="请输入密码"></el-input>
              </el-form-item>
              <el-form-item label="邮箱" label-width="70px">
                <el-input clearable v-model="userInfo.email" placeholder="请输入邮箱"></el-input>
              </el-form-item>
              <el-form-item label="手机" label-width="70px">
                <el-input clearable v-model="userInfo.mobile" placeholder="请输入手机"></el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="AddDialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
          </el-dialog>
        </el-col>
      </el-row>
      <el-table
        :data="userList"
        style="width: 100%"
        max-height="450"
        border stripe>
        <el-table-column type="index" label="#" align="center"></el-table-column>
        <el-table-column
          prop="username"
          label="姓名"
          width="180" align="center">
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
          width="180" align="center">
        </el-table-column>
        <el-table-column
          prop="mobile"
          label="电话"
          width="180" align="center">
        </el-table-column>
        <el-table-column
          prop="role_name"
          label="角色"
          width="180" align="center">
        </el-table-column>
        <el-table-column
          prop="mg_state"
          label="状态"
          width="180" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#409EFF"
              inactive-color="#DCDFE6" @change="saveStateChange(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="openEdit(scope.row)"><i class="el-icon-edit"></i></el-button>
            <el-dialog
              title="修改用户信息"
              :visible.sync="UpdateDialogVisible"
              width="40%"
              @close="$refs.updateUserRef.clearValidate()">
              <el-form :model="updateUserInfo" :rules="updateRules" ref="updateUserRef">
                <el-form-item label="用户名" label-width="70px" hide-required-asterisk>
                  <el-input :disabled="true" clearable v-model="updateUserInfo.username" placeholder="请输入用户名"></el-input>
                </el-form-item>
                <el-form-item prop="email" label="邮箱" label-width="70px">
                  <el-input clearable v-model="updateUserInfo.email" placeholder="请输入邮箱"></el-input>
                </el-form-item>
                <el-form-item prop="mobile" label="手机" label-width="70px">
                  <el-input clearable v-model="updateUserInfo.mobile" placeholder="请输入手机"></el-input>
                </el-form-item>
              </el-form>
              <span slot="footer" class="dialog-footer">
                <el-button @click="UpdateDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="updateUser()">确 定</el-button>
              </span>
            </el-dialog>
            <el-popover
              placement="top"
              width="160"
              v-model="scope.id"
              :ref="scope.$index">
              <p>删除之后无法恢复</p>
              <p>你确定删除吗？</p>
              <div style="text-align: right; margin: 0">
                <el-button size="mini" type="text" @click="scope._self.$refs[scope.$index].doClose(),cancelDeleteTooltip()">取消</el-button>
                <el-button type="primary" size="mini" @click="scope._self.$refs[scope.$index].doClose(),deleteHandler(scope.row)">确定</el-button>
              </div>
              <el-button class="deleteBtn" slot="reference" size="mini" type="danger"><i class="el-icon-delete"></i></el-button>
              <!--              <el-button slot="reference">删除</el-button>-->
            </el-popover>
            <el-tooltip content="分配角色" placement="top" :enterable="false">
              <el-button size="mini" type="warning" @click="openDistributionDialog(scope)"><i class="el-icon-setting"></i></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="paramList.pagenum"
        :page-sizes="[4, 8, 10, 15]"
        :page-size="paramList.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalPage">
      </el-pagination>
    </el-card>
    <!--分配角色-->
    <el-dialog
      title="分配用户角色"
      :visible.sync="distuibutionRolesVisible"
      width="40%"
      @close="setDistuibutionClose"
    >
      <p>当前用户: <span>{{theRowUserInfo.username}}</span></p>
      <p>当前角色: <span>{{theRowUserInfo.role_name}}</span></p>
      <el-row :gutter="4">
        <el-col :span="4">
          该分配的角色
        </el-col>
        <el-col :span="20">
          <el-select v-model="selectValue" placeholder="请选择" clearable >
            <el-option
              v-for="item in RoleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
              >
            </el-option>
          </el-select>
        </el-col>
      </el-row>

      <span slot="footer" class="dialog-footer">
              <el-button @click="distuibutionRolesVisible = false">取 消</el-button>
              <el-button type="primary" @click="distributionRole">确 定</el-button>
            </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  created () {
    const currentPage = window.sessionStorage.getItem('currentPage')
    const pageSize = window.sessionStorage.getItem('pageSize')
    if (!currentPage) {
      this.paramList.pagenum = 1
    } else {
      this.paramList.pagenum = parseInt(currentPage)
    }
    if (!pageSize) {
      this.paramList.pagesize = 8
    } else {
      this.paramList.pagesize = parseInt(pageSize)
    }
    this.getUserList()
  },
  data () {
    return {
      paramList: {
        query: '',
        pagenum: 1,
        pagesize: 8
      },
      // 总记录数
      totalPage: 0,
      // 当前页码
      // pagenum: 1,
      userList: [],
      // 添加弹框
      AddDialogVisible: false,
      // 更新对话弹框
      UpdateDialogVisible: false,
      userInfo: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 修改信息存储对象 通过ID查询出的结果
      updateUserInfo: {},
      visible: false,
      addRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入用户名密码', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ]
      },
      updateRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { min: 5, max: 11, message: '长度在 5 到 11 个字符', trigger: 'blur' }
        ]
      },
      // 分配角色弹框
      distuibutionRolesVisible: false,
      // 角色数据数组
      RoleList: [],
      // 角色授权选中行数据
      theRowUserInfo: {},
      // 选中的值
      selectValue: ''
    }
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$http.get('users', { params: this.paramList })
      if (res.meta.status !== 200) {
        return this.$message.error('数据获取异常')
      }

      this.totalPage = res.data.total
      this.pagenum = res.data.pagenum
      this.userList = []
      this.userList = res.data.users
    },
    // pagesize改变的时候的处理函数
    handleSizeChange (val) {
      window.sessionStorage.setItem('pageSize', val)
      this.paramList.pagesize = val
      this.getUserList()
    },
    // 添加用户
    addUser () {
      // 不知道为什么要加settimeout这个 好像是防抖 有时候无法通过$refs来获取组件
      setTimeout(() => {
        this.$refs.addUserRef.validate(async val => {
          if (!val) return this.$message.error('请输入用户添加信息')
          const { data: res } = await this.$http.post('users', this.userInfo)
          if (res.meta.status !== 201) {
            return this.$message.error('添加失败')
          }
          this.AddDialogVisible = false
          this.getUserList()
          this.$message.success('添加成功')
        })
      }, 0)
    },
    // 当前页码改变的处理函数
    handleCurrentChange (val) {
      window.sessionStorage.setItem('currentPage', val)
      window.sessionStorage.getItem('currentPage')
      this.paramList.pagenum = val
      this.getUserList()
    },
    queryUserBykey () {
      this.paramList.pagenum = 1
      this.getUserList()
    },
    cancelDeleteTooltip () {
      this.$message.info('已取消删除')
    },
    async deleteHandler (row) {
      const { data: res } = await this.$http.delete(`users/${row.id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success('删除成功')
      this.getUserList()
    },
    // 修改用户
    updateUser () {
      // 防抖
      // dom还没有更新
      this.$nextTick(function () {
        // dom已更新
        this.$refs.updateUserRef.validate(async val => {
          if (!val) return this.$message.error('字段不合法')
          const { data: res } = await this.$http.put(`users/${parseInt(this.updateUserInfo.id)}`, this.updateUserInfo)
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }
          this.getUserList()
          this.UpdateDialogVisible = false
          this.$message.success(res.meta.msg)
        })
      })
    },
    // 打开修改对话框
    openEdit (row) {
      // 根据用户ID去查询用户信息 然后储存到updateUserInfo对象中去
      this.UpdateDialogVisible = true
      const that = this
      this.$http.get(`users/${row.id}`).then(res => {
        if (res.data.meta.status !== 200) {
          return that.$message.error(res.data.meta.msg)
        }
        that.updateUserInfo = res.data.data
      }, () => {
        return that.$message('接口错误')
      })
    },
    async saveStateChange (newState) {
      const { data: res } = await this.$http.put(`users/${newState.id}/state/${newState.mg_state}`)
      if (res.meta.status !== 200) {
        newState.mg_state = !newState.mg_state
        return this.$message.error('接口有错')
      }
      this.$message.success('状态修改成功')
    },
    // 分配角色
    async openDistributionDialog (role) {
      this.theRowUserInfo = role.row
      this.distuibutionRolesVisible = true
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.RoleList = res.data
    },
    async distributionRole () {
      // 获取角色ID
      // 对选没选择做一个判断 如果没有选择的话就提示用户信息
      if (!this.selectValue) {
        return this.$message.error('请选择要分配的角色')
      }
      // 将用户ID 和角色ID一起传过来
      const { data: res } = await this.$http.put(`users/${this.theRowUserInfo.id}/role`, { rid: this.selectValue })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.distuibutionRolesVisible = false
      this.getUserList()
    },
    // 弹框关闭之后的操作
    setDistuibutionClose () {
      this.selectValue = ''
      this.theRowUserInfo = {}
    }
    // 获取角色ID
    /* async getRoleId () {
      console.log(this.selectValue)
      const { data: res } = await this.$http.get(`users/${this.theRowUserInfo.id}`)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      return res.data.rid
    } */
  },
  watch: {
    // 如果当前页为最后一页删除掉最后一条数据之后返回到前一页
    // 思路监听总条数 如果总条数等于当前页码-1*页面数据大小 并且总数据条数不能为空
    totalPage () {
      if (this.totalPage === (this.paramList.pagenum - 1) * this.paramList.pagesize && this.totalPage !== 0) {
        this.paramList.pagenum -= 1
        // 获取列表数据
        this.getUserList()
      }
    }
  }
}
</script>
<style lang="less" scoped>
.deleteBtn{
  margin: 0 20px;
}
.el-row{
  display: flex;
  align-items: center;
}
</style>
